package com.rc.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.provider.Contract;
import com.rc.activity.sync.util.TripSync;
import com.rc.db.DatabaseSupport;
import com.rc.net.NetSupport;
import com.rc.object.BaseObject;
import com.rc.util.Const;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class TripCreateNew extends BaseActivity implements OnClickListener {

	public static void callIntent(Context ct) {
		Intent it = new Intent(ct, TripCreateNew.class);
		ct.startActivity(it);
	}

	private LinearLayout llSave, llCancel, llReset, llContent, llProgress;
	private TextView txtEndDate, txtStartDate, txtTripName, txtLeg, txtFrom,
			txtTo, txtTripReference, txtMemo;
	private tbl_Trip objTrip;
	private Calendar cal;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.trip_edit);
		((TextView) findViewById(R.id.lbTitle))
				.setText(getString(R.string.create_new_trip));

		// register
		llSave = (LinearLayout) findViewById(R.id.llSave);
		llReset = (LinearLayout) findViewById(R.id.llReset);
		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		llProgress = (LinearLayout) findViewById(R.id.llProgress);
		llContent = (LinearLayout) findViewById(R.id.llContent);
		txtEndDate = (TextView) findViewById(R.id.txtEndDate);
		txtStartDate = (TextView) findViewById(R.id.txtStartDate);
		txtTripName = (TextView) findViewById(R.id.txtTripName);
		txtLeg = (TextView) findViewById(R.id.txtLeg);
		txtFrom = (TextView) findViewById(R.id.txtFrom);
		txtTo = (TextView) findViewById(R.id.txtTo);
		txtTripReference = (TextView) findViewById(R.id.txtTripReference);
		txtMemo = (TextView) findViewById(R.id.txtMemo);

		// funtion
		txtTripReference.setEnabled(false);
		llSave.setOnClickListener(this);
		llCancel.setOnClickListener(this);
		txtEndDate.setOnClickListener(this);
		txtStartDate.setOnClickListener(this);
		llReset.setOnClickListener(this);

		// set default date for TEXTVIEW date of birth
		getDefaultInfor();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llReset:
			txtTripName.setText("");
			txtLeg.setText("");
			txtFrom.setText("");
			txtTo.setText("");
			txtMemo.setText("");
			getDefaultInfor();
			break;
		case R.id.llSave:
			llContent.setVisibility(View.GONE);
			llProgress.setVisibility(View.VISIBLE);
			if (llProgress.getVisibility() == View.VISIBLE) {
				if (DatabaseSupport.checkStartDateEndDate(txtEndDate.getText()
						.toString(), txtStartDate.getText().toString(),
						TripCreateNew.this)) {
					if (insertData() != null) {
						finish();
					}
				} else {
					llContent.setVisibility(View.VISIBLE);
					llProgress.setVisibility(View.GONE);
					showToast(R.string.you_cannot_have_a_trip_start_before_the_end_of_another_trip_on_record);
				}
			}

			break;
		case R.id.llCancel:
			finish();
			break;
		case R.id.txtEndDate:
			showDatePickerDialog(true);
			break;
		case R.id.txtStartDate:
			showDatePickerDialog(false);
			break;
		default:
			break;
		}
	}

	/**
	 * update database SQLite
	 */

	private Uri insertData() {
		if (vaildateUI()) {
			objTrip = new tbl_Trip();
			objTrip = getDataFromUI();
			Uri uri = null;
			if (Util.isNetworkActivated(TripCreateNew.this)) {
				ArrayList<tbl_Trip> arrTrips = new ArrayList<tbl_Trip>();
				arrTrips.add(objTrip);
				if ("".equals(Const.AUTHENKEY)) {
					Const.AUTHENKEY = DatabaseSupport.getTbl_User(
							TripCreateNew.this).getToken();
				}
				ArrayList<BaseObject> arrBase = new ArrayList<BaseObject>();
				arrBase = NetSupport.insertTrips(arrTrips);
				objTrip.setIsCreate("");

				for (BaseObject baseObject : arrBase) {
					if ("fail".equals(baseObject.getParam(TripSync.keys[0]))) {
						String msg = baseObject.getParam(TripSync.keys[2]);
						msg = msg.replace("\"", "");
						msg = msg.replace("[", "");
						msg = msg.replace("]", "");
						showToast(msg);
						finish();
					} else {
						objTrip.setTripID(baseObject
								.getParamLong(TripSync.keys[1]));
						uri = this.getContentResolver().insert(
								Contract.CONTENT_URI_TRIP,
								objTrip.getContentValues());
					}

				}
				if (uri != null) {
					ReceiptBox.callIntent(TripCreateNew.this,
							objTrip.getTripID() + "", 5);
				} else {
					return null;
				}

			} else {
				return this.getContentResolver().insert(
						Contract.CONTENT_URI_TRIP, objTrip.getContentValues());
			}

		}
		return null;
	}

	/**
	 * Validate info UI
	 */
	private boolean vaildateUI() {
		if (!Util.validateText(txtTripName)) {
			Util.setError((EditText) txtTripName,
					getString(R.string.input_trip_name));
		} else if (!Util.validateText(txtFrom)) {
			Util.setError((EditText) txtFrom, getString(R.string.input_from));
		} else if (!Util.validateText(txtTo)) {
			Util.setError((EditText) txtTo, getString(R.string.input_to));
		} else {
			return true;
		}
		return false;
	}

	/**
	 * get data from UI
	 */

	@SuppressLint("SimpleDateFormat")
	private tbl_Trip getDataFromUI() {
		objTrip = new tbl_Trip();
		objTrip.setTripID(Long.valueOf(Util.getCurrentTime()));
		objTrip.setName(txtTripName.getText().toString());
		objTrip.setMemo(txtMemo.getText().toString());
		int leg = "".endsWith(txtLeg.getText().toString()) ? 0 : 1;
		objTrip.setTripLeg(leg + "");
		objTrip.setDeparture(txtFrom.getText().toString());
		objTrip.setArrival(txtTo.getText().toString());
		objTrip.setMemo(txtMemo.getText().toString());
		objTrip.setStartDate(txtStartDate.getText().toString());
		objTrip.setEndDate(txtEndDate.getText().toString());
		int startInt = Util.parseDateForInt(txtStartDate.getText().toString());
		objTrip.setStartDateInt(startInt);
		objTrip.setFilterDate(startInt);
		objTrip.setIsDelete("");
		objTrip.setIsCreate("1");
		objTrip.setIsUpdate("");
		objTrip.setAmount("0.00");
		long reportID = 0;
		objTrip.setReport_ID(reportID);
		objTrip.setUserID(DatabaseSupport.getTbl_User(TripCreateNew.this)
				.getUserID() + "");
		int endInt = Util.parseDateForInt(txtEndDate.getText().toString());
		Date date = Calendar.getInstance().getTime();
		SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");

		int datenowInt = Util.parseDateForInt(dateformat.format(date));
		String tripType = "";
		if (endInt < datenowInt && startInt < datenowInt) {
			tripType = getString(R.string.past_trips);
		} else if (endInt > datenowInt && startInt > datenowInt) {
			tripType = getString(R.string.upcoming_trips);
		} else {
			tripType = getString(R.string.current_trips);
		}
		objTrip.setType(tripType);
		objTrip.setEndDateInt(endInt);
		;
		objTrip.setReference(txtTripReference.getText().toString());
		return objTrip;
	}

	private void getDefaultInfor() {
		cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		dft = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
		String strDate = dft.format(cal.getTime());
		strDate = strDate.replace("/", "-");
		String startDate = DatabaseSupport.checkStartDate(strDate,
				TripCreateNew.this);
		txtStartDate.setText(startDate);
		String endDate = Util.addDate(startDate, 3);
		endDate = DatabaseSupport.checkEndDate(endDate, startDate,
				TripCreateNew.this);
		txtEndDate.setText(endDate);
		txtTripReference.setText(DatabaseSupport.validateReference(
				"T" + Util.parseDateForInt(startDate), TripCreateNew.this));
	}

	/**
	 * isEndDate = true - > show End isEndDate = false - > show start
	 */
	public void showDatePickerDialog(final boolean isEndDate) {
		int date = 0, month = 0, year = 0;

		OnDateSetListener callback = new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// Date
				String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth
						+ "";
				String month = (monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1)
						: (monthOfYear + 1) + "";
				String textDate = day + "-" + month + "-" + year;
				if (isEndDate) {
					txtEndDate.setText(DatabaseSupport.checkEndDate(textDate,
							txtStartDate.getText().toString(),
							TripCreateNew.this));
				} else {
					int startInt = Util.parseDateForInt(textDate);
					int endInt = Util.parseDateForInt(txtEndDate.getText()
							.toString());
					if (endInt >= startInt) {
						txtStartDate.setText(DatabaseSupport.checkEndDate(
								textDate, txtStartDate.getText().toString(),
								TripCreateNew.this));
						txtTripReference.setText(DatabaseSupport
								.validateReference(
										"R" + Util.parseDateForInt(textDate),
										TripCreateNew.this));
					}

				}

			}
		};
		String s = "";
		if (isEndDate) {
			s = txtEndDate.getText() + "";
		} else {
			s = txtStartDate.getText() + "";
		}
		if ("".equals(s)) {
			return;
		}
		s = s.replace("/", "-");
		if (s.indexOf("-") >= 0) {
			String strArrtmp[] = s.split("-");
			date = Integer.parseInt(strArrtmp[0]);
			month = Integer.parseInt(strArrtmp[1]) - 1;
			year = Integer.parseInt(strArrtmp[2]);

			DatePickerDialog pic = new DatePickerDialog(TripCreateNew.this,
					callback, year, month, date);
			if (isEndDate) {
				pic.setTitle(getString(R.string.choose_end_date));
			} else {
				pic.setTitle(getString(R.string.choose_start_date));
			}
			pic.show();
		}

	}

}
